package com.sinosoft.cloud.access.limiting;

import com.sinosoft.cloud.access.net.AccessControl;
import com.sinosoft.cloud.common.SpringContextUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import static com.sinosoft.cloud.access.handler.AbstractHandler.messageHashTable;

/**
 * Created by Administrator on 2017-12-22.
 */
@Component
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class CircuiBreakerServiceImpl implements CircuiBreaker{

    private final Log logger = LogFactory.getLog(getClass());
    /**
     * 创建由spring管理的读取配置文件对象
     */
    AccessControl accessControl = SpringContextUtils.getBeanByClass(AccessControl.class);

    private String accessName;

    /**
     * 限流处理
     * <p>
     * threadPoolExecutor 是Netty的运行线程池. threadPoolExecutor中正在运行的现场就是当前系统整处理的负载量.
     *
     * @return
     */
    @Override
    public Boolean rateLimite() {
    /*获取配置文件中配置的阈值*/
        int maxCount = accessControl.getThreshold();
        int threadKeyCount = -1;

        threadKeyCount = messageHashTable.size();

        Boolean result = false;

        logger.info("当前并发数量为" + threadKeyCount + ",当前阈值为" + maxCount);
        if (threadKeyCount > maxCount) {
            result = true;
        }
        return result;
    }

    @Override
    public void setAccessName(String accessName) {
        this.accessName = accessName;
    }

    public String getAccessName() {
        return accessName;
    }
}
